package com.centling.smartSealForPhone.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.TextView;

import com.centling.smartSealForPhone.R;
import com.centling.smartSealForPhone.activity.TitleBarActivity;
import com.centling.smartSealForPhone.application.SmartSeal;
import com.centling.smartSealForPhone.constants.SPConstants;
import com.centling.smartSealForPhone.db.DbControl;
import com.centling.smartSealForPhone.service.UploadImageService;
import com.centling.smartSealForPhone.utils.SPUtil;
import com.centling.smartSealForPhone.utils.ShowDialog;
import com.centling.smartSealForPhone.utils.ShowToast;
import com.example.localalbum.common.ImageUtils;
import com.example.localalbum.common.LocalImageHelper;
import com.example.localalbum.ui.ImageScrollView;
import com.example.localalbum.ui.LocalAlbum;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * @author fionera
 */
public class StampImgActivity
        extends TitleBarActivity
        implements View.OnClickListener {

    private ImageScrollView uploadScrollView;

    private String applyId;
    private ArrayList<String> recordIds;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_stamp_img);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            applyId = bundle.getString("applyId");
            recordIds = bundle.getStringArrayList("recordIds");
        } else {
            ShowToast.shortTime("获取用印申请信息失败");
            mActivity.finish();
        }

        setTitleBarText("上传图片");

        initView();
    }

    private void initView() {
        TextView tvBreak = findViewById(R.id.tv_stamp_break);
        tvBreak.setOnClickListener(this);
        TextView tvUpload = findViewById(R.id.tv_stamp_upload_picture);
        tvUpload.setOnClickListener(this);
        uploadScrollView = findViewById(R.id.isv_stamp_upload);
        LocalImageHelper.getInstance().setTotalSize(recordIds.size());
        uploadScrollView.setOnAddListener(new ImageScrollView.OnAddListener() {
            @Override
            public void onClick() {
                LocalImageHelper.getInstance().getCheckedItems().clear();
                LocalImageHelper.getInstance().setCurrentSize(uploadScrollView.getFiles().size());
                startActivityForResult(new Intent(mContext, LocalAlbum.class),
                        ImageUtils.REQUEST_CODE_GET_IMAGE_BY_CROP);
            }
        });
        uploadScrollView.setOnDeleteListener(new ImageScrollView.OnDeleteListener() {
            @Override
            public void onDelete(final int pos) {
                new AlertDialog.Builder(mContext).setTitle("删除图片").setMessage("删除这张图片以重新添加")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                uploadScrollView.getFiles().remove(pos);
                                uploadScrollView.getAdapter().notifyDataSetChanged();
                                LocalImageHelper.getInstance().setCurrentSize(
                                        uploadScrollView.getFiles().size());
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_stamp_break:
                ShowDialog.showSelectDialog(mContext, "跳过上传", "你确定要跳过上传吗", "",
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mActivity.finish();
                            }
                        });
                break;
            case R.id.tv_stamp_upload_picture:
                int fileSize = uploadScrollView.getFiles().size();
                if (recordIds.size() == 0) {
                    mActivity.finish();
                } else if (fileSize < recordIds.size()) {
                    ShowDialog.showSelectDialog(mContext, "上传图片", "图片数量不足你确定要上传吗",
                            String.format(Locale.CHINA, "共%d张", fileSize),
                            new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    tryToUploadImages();
                                }
                            });
                } else if (fileSize > recordIds.size()) {
                    ShowDialog.showConfirmDialog(mContext, "上传图片", "图片数量不可大于用印次数", null);
                } else {
                    tryToUploadImages();
                }
                break;
            default:
                break;
        }
    }

    private void tryToUploadImages() {
        List<LocalImageHelper.LocalFile> files = uploadScrollView.getFiles();
        for (int i = 0; i < files.size(); i++) {
            DbControl.getInstance().insertData("2", applyId, SPUtil.getString(SPConstants.USER_ID),
                    recordIds.get(i), files.get(i).getPath());
        }
        ConnectivityManager connectMgr = (ConnectivityManager) SmartSeal.getInstance()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = null;
        if (connectMgr != null) {
            info = connectMgr.getActiveNetworkInfo();
        }

        if (info != null) {
            if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                mContext.startService(
                        new Intent(mContext, UploadImageService.class));
                mActivity.finish();
            } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
                ShowDialog.showSelectDialog(mContext, "警告", "您当前正在使用移动网络，将会产生大量流量", "推荐在WIFI下上传",
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mContext.startService(
                                        new Intent(mContext, UploadImageService.class));
                                mActivity.finish();
                            }
                        }, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mActivity.finish();
                            }
                        });
            }
        } else {
            mActivity.finish();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == ImageUtils.REQUEST_CODE_GET_IMAGE_BY_CROP) {
            if (LocalImageHelper.getInstance().isResultOk()) {
                LocalImageHelper.getInstance().setResultOk(false);
                List<LocalImageHelper.LocalFile> localFiles = LocalImageHelper.getInstance()
                        .getCheckedItems();
                LocalImageHelper.getInstance().setCurrentSize(uploadScrollView.getFiles().size());
                uploadScrollView.addFiles(localFiles);
            }
        }
    }
}
